﻿//Creative Commons - GNU Lesser General Public License (http://creativecommons.org/licenses/LGPL/2.1/)
/*  ----------------------------------------------------------------------------
 *  SharePointLovers.com
 *  ----------------------------------------------------------------------------
 *  Replace WebPart Instances
 *  ----------------------------------------------------------------------------
 *  File:       ReplaceWebpartInstance.aspx.cs
 *  Author:     jajayaraman
 *  ----------------------------------------------------------------------------
 */
using System;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.WebControls;
using System.Web.UI;
using System.IO;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Data.SqlClient;
using System.Data;
using WebPart = Microsoft.SharePoint.WebPartPages.WebPart;

namespace SharePoint_Replace_WebParts.Layouts.SharePoint_Replace_WebParts
{
    public partial class ReplaceWebpartInstance : LayoutsPageBase
    {
        public String Fileurls = string.Empty;
        protected void PageLoad(object sender, EventArgs e)
        {
            try
            {


                //                AWACWebPartPagesRef.WebPartPagesWebService svc = new AWACWebPartPagesRef.WebPartPagesWebService();
                //                svc.UseDefaultCredentials = true;
                //              Controls.Add( new LiteralControl("<BR>"));
                //                

                //                using (SPSite site = new SPSite(""))
                //                {
                //                    using (SPWeb web = site.OpenWeb())
                //                    {

                //                    }
                //                }



                //                //string result = svc.GetWebPartPage("default.aspx", AWACWebPartPagesRef.SPWebServiceBehavior.Version3);
                //                //Controls.Add(new LiteralControl(result+"<br>"));

                //                //Controls.Add(new LiteralControl("-----------------------------------------------------------------------------------<br>"));
                //                //XmlNode resultNode = svc.GetWebPartProperties2(pageUrl, AWACWebPartPagesRef.Storage.Shared, AWACWebPartPagesRef.SPWebServiceBehavior.Version3);
                //                //Controls.Add(new LiteralControl(resultNode.InnerXml + "<br>"));
                //                //Controls.Add(new LiteralControl("-----------------------------------------------------------------------------------<br>"));
                //                //Controls.Add(new LiteralControl(resultNode.InnerText + "<br>"));
                //                //Controls.Add(new LiteralControl("-----------------------------------------------------------------------------------<br>"));
                //                //Controls.Add(new LiteralControl(resultNode.OuterXml + "<br>"));
            }
            catch (Exception ex)
            {
                Controls.Add(new LiteralControl(ex.Message));
            }

        }
        private string GetSourceCode(string fileurl)
        {
            string htmlsource = string.Empty;
            try
            {
                using (var site = new SPSite(fileurl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        try
                        {
                            //SPFile file = web.GetFile(fileurl);
                            //byte[] fileConetentBuff = file.OpenBinary();
                            //var encoding = new ASCIIEncoding();
                            //string fileContent = encoding.GetString(fileConetentBuff);
                            //htmlsource = fileContent;
                            var file = (SPFile)web.GetObject(fileurl);
                            var stream = file.OpenBinaryStream();
                            var sr = new StreamReader(stream);
                            var sw = new StreamWriter(stream);

                            htmlsource = sr.ReadToEnd();
                        }
                        catch (Exception)
                        {
                            try
                            {
                                var file = (SPListItem)web.GetObject(fileurl);
                                SPFile file1 = web.GetFile(fileurl);



                                //var file = (SPFile)web.GetObject(fileurl);
                                //var stream = file.OpenBinaryStream();
                                //var sr = new StreamReader(stream);



                                //byte[] fileConetentBuff = file1.OpenBinaryStream();
                                //var encoding = new ASCIIEncoding();
                                //string fileContent = encoding.GetString(fileConetentBuff);
                                //htmlsource = fileContent;
                                //  var file = (SPListItem)web.GetObject(fileurl);
                                var stream = file1.OpenBinaryStream();
                                var sr = new StreamReader(stream);
                                //  var sw = new StreamWriter(stream);
                                htmlsource = sr.ReadToEnd();
                            }
                            catch (Exception ex)
                            {
                               // Loggings.LogError(ex);
                            }

                        }

                    }
                }

                //byte[] buffer = Encoding.UTF8.GetBytes(s);
                //var ms = new MemoryStream(buffer, true);
                //file.SaveBinary(ms);
                //stream.Dispose();
                //web.AllowUnsafeUpdates = false;
                //success = true;
            }
            catch (Exception ex)
            {
                lblerror.Text = ex.Message;
            }
            return htmlsource;
        }
        private static bool ReplaceWpInstances(SPWeb web, string fileurl, string find, string replace)
        {
            bool success = false;
            try
            {
                web.AllowUnsafeUpdates = true;
                var file = (SPFile)web.GetObject(fileurl);
                var stream = file.OpenBinaryStream();
                var sr = new StreamReader(stream);
                var sw = new StreamWriter(stream);
                var s = sr.ReadToEnd();
                s = s.Replace(find, replace);
                byte[] buffer = Encoding.UTF8.GetBytes(s);
                var ms = new MemoryStream(buffer, true);
                file.SaveBinary(ms);
                stream.Dispose();
                web.AllowUnsafeUpdates = false;
                success = true;
            }
            catch (Exception ex)
            {
              //  Loggings.LogError(ex);
            }
            return success;
        }
        private static void ReplaceWebPart(string siteUrl, string oldwebPartName, string newWebPartName, bool all)
        {
            try
            {
                using (var site = new SPSite(siteUrl))
                {
                    if (all)
                    {
                        foreach (SPWeb web in site.AllWebs)
                        {

                            foreach (var file in web.Files.Cast<SPFile>().Where(file => file.Name.EndsWith("aspx")))
                            {
                                ReplaceWpInstances(web, file.ServerRelativeUrl, oldwebPartName, newWebPartName);
                            }
                            //  var pagesTemplateType = (SPListTemplateType)Enum.Parse(typeof(SPListTemplateType), "850");
                            foreach (var documentLibrary in web.Lists.Cast<SPList>().Where(list => list.BaseTemplate == SPListTemplateType.WebPageLibrary || (list.BaseTemplate == SPListTemplateType.DocumentLibrary && list.Title.Contains("Pages")) || (list.Title.Contains("Pages"))))
                            {
                                foreach (var file in documentLibrary.Items.Cast<SPListItem>().Where(item => item.File.Name.EndsWith("aspx")).Select(item => item.File))
                                {
                                    ReplaceWpInstances(web, file.ServerRelativeUrl, oldwebPartName, newWebPartName);
                                }
                            }
                        }
                    }
                    else
                    {
                        SPWeb web = site.OpenWeb();
                        ReplaceWpInstances(web, siteUrl, oldwebPartName, newWebPartName);
                    }

                }
            }
            catch (Exception ex)
            {

               // Loggings.LogError(ex);
            }
        }
        private static string FindWebPart(string siteUrl, string webPartName, bool wp)
        {
            string url = string.Empty;
            try
            {

                using (var site = new SPSite(siteUrl))
                {
                    foreach (SPWeb web in site.AllWebs)
                    {
                        foreach (var file in web.Files.Cast<SPFile>().Where(file => file.Name.EndsWith("aspx")))
                        {
                            try
                            {
                              //  Loggings.LogMessage(file.Url);
                                url += (wp) ? (string.IsNullOrEmpty(FindWebPartOnPage(webPartName, file))) ? string.Empty : web.Site.MakeFullUrl(FindWebPartOnPage(webPartName, file)) + "," : web.Site.MakeFullUrl(file.ServerRelativeUrl) + ",";
                            }
                            catch (Exception ex)
                            {// Loggings.LogError(ex);
                            }
                        }
                        // var pagesTemplateType = (SPListTemplateType)Enum.Parse(typeof(SPListTemplateType), "850");
                        //  foreach (var documentLibrary in web.Lists.Cast<SPList>().Where(list => list.BaseTemplate == pagesTemplateType || (list.BaseTemplate == SPListTemplateType.DocumentLibrary && list.Title.Contains("Pages")) || (list.Title.Contains("Pages"))))
                        foreach (var documentLibrary in web.Lists.Cast<SPList>().Where(list => list.BaseTemplate == SPListTemplateType.WebPageLibrary || (list.BaseTemplate == SPListTemplateType.DocumentLibrary) || (list.Title.Contains("Pages"))))
                        {
                            try
                            {
                                if (!documentLibrary.Title.Contains("Project Documents"))
                                {

                                    foreach (var file in documentLibrary.Items.Cast<SPListItem>().Where(item => item.File.Name.EndsWith("aspx")).Select(item => item.File))
                                    {
                                        try
                                        {
                                          //  Loggings.LogMessage(file.Url);
                                            url += (wp) ? (string.IsNullOrEmpty(FindWebPartOnPage(webPartName, file))) ? string.Empty : web.Site.MakeFullUrl(FindWebPartOnPage(webPartName, file)) + "," : web.Site.MakeFullUrl(file.ServerRelativeUrl) + ",";

                                        }
                                        catch (Exception ex)
                                        { //Loggings.LogError(ex); 
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            { //Loggings.LogError(ex);
                            }


                        }
                        web.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {

              //  Loggings.LogError(ex);
            }
            return url;
        }
        private static string FindWebPartOnPage(string webPartName, SPFile file)
        {
            string text = string.Empty;
            try
            {
                using (var webPartManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared))
                {
                    text = (webPartManager.WebParts.Cast<WebPart>().Any(webPart => webPart.GetType().Name == webPartName)) ? file.ServerRelativeUrl + "," : string.Empty;
                    webPartManager.Web.Dispose();
                }
            }
            catch (Exception ex)
            {
              //  Loggings.LogError(ex);
            }
            return text;
        }
        protected void WebPagesClick(object sender, EventArgs e)
        {
            try
            {
                lstLinks.Items.Clear();
                Dictionary<string, string> dLinks = new Dictionary<string, string>();

                string Urls = FindWebPart(txtsiteurl.Text, txtwpname.Text, false);
                char[] stringSeparators = { ',' };

                string[] IndLink = Urls.Split(stringSeparators);
                foreach (string s in IndLink)
                {
                    if (!string.IsNullOrEmpty(s))
                        if (!dLinks.ContainsKey(s))
                            dLinks.Add(s, s);
                }
                lstLinks.DataTextField = "Value";
                lstLinks.DataValueField = "Key";
                lstLinks.DataSource = dLinks;
                lstLinks.DataBind();
            }
            catch (Exception ex)
            {

             //   Loggings.LogError(ex);
            }
            //   pnlwebpages.Controls.Add(new LiteralControl(FindWebPart(txtsiteurl.Text, txtwpname.Text, false)));
        }
        protected void LsLinksSelectionChanged(object sender, EventArgs e)
        {
            try
            {
                pnlcontentarea.Controls.Add(new LiteralControl(Server.HtmlEncode(GetSourceCode(lstLinks.SelectedValue.ToString()))));
            }
            catch (Exception ex)
            {
               // Loggings.LogError(ex);
            }
        }
        protected void BtnexecuteWebpartsClick(object sender, EventArgs e)
        {
            try
            {
                lstLinks.Items.Clear();
                Dictionary<string, string> dLinks = new Dictionary<string, string>();
                string Urls = FindWebPart(txtsiteurl.Text, txtwpname.Text, true);
                char[] stringSeparators = { ',' };
                string[] IndLink = Urls.Split(stringSeparators);
                foreach (string s in IndLink)
                {
                    if (!string.IsNullOrEmpty(s))
                        if (!dLinks.ContainsKey(s))
                            dLinks.Add(s, s);
                }
                lstLinks.DataTextField = "Value";
                lstLinks.DataValueField = "Key";
                lstLinks.DataSource = dLinks;
                lstLinks.DataBind();
            }
            catch (Exception ex)
            {

              //  Loggings.LogError(ex);
            }
        }
        protected void BtngetsourceClick(object sender, EventArgs e)
        {
            try
            {
                if (rdolstScope.SelectedValue == "Page")
                {
                    ReplaceWebPart(lstLinks.SelectedValue, txttofind.Text, txttoreplacewith.Text, false);
                }
                else if (rdolstScope.SelectedValue == "Web")
                {
                }
                else if (rdolstScope.SelectedValue == "Site")
                {
                    ReplaceWebPart(txtsiteurl.Text, txttofind.Text, txttoreplacewith.Text, true);
                }
            }

            catch (Exception ex)
            {

               // Loggings.LogError(ex);
            }
            //  pnlcontentarea.Controls.Add(new LiteralControl(Server.HtmlEncode(GetSourceCode(txtpageurl.Text))));
        }
        protected void BtnreplaceClick(object sender, EventArgs e)
        {
            try
            {
                string webPartName = string.Empty;
                using (SPSite site = new SPSite(lstLinks.SelectedValue))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        var file = (SPFile)web.GetObject(lstLinks.SelectedValue);
                        using (var webPartManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared))
                        {
                            foreach (WebPart wp in webPartManager.WebParts)
                            {
                                if (webPartManager.WebParts.Cast<WebPart>().Any(webPart => webPart.GetType().Name == webPartName))
                                {
                                    // wp.
                                }
                            }

                            //webPartManager.WebParts[2].WebBrowsableObject.ToString();
                            //System.Collections.Generic.IEnumerable webpartList = from System.Web.UI.WebControls.WebParts.WebPart webpart in webPartManager.WebParts
                            //                          where webpart.Title == webPartName
                            //                          select webpart;

                            //WebPart wp = webPartManager.WebParts.Cast<WebPart>().Any(webPart => webPart.GetType().Name == webPartName);

                            //text = (webPartManager.WebParts.Cast<WebPart>().Any(webPart => webPart.GetType().Name == webPartName)) ? file.ServerRelativeUrl + "," : string.Empty;
                            webPartManager.Web.Dispose();
                        }
                    }
                }
            }
            catch (Exception ex)
            {

           //     Loggings.LogError(ex);
            }

            //  ReplaceWebPart(txtsiteurl.Text, txttofind.Text, txttoreplacewith.Text, true);
        }
        protected void BtnreplacePageClick(object sender, EventArgs e)
        {
            //    ReplaceWebPart(txtpageurl.Text, txttofind.Text , txttoreplacewith.Text,false);
        }
        protected void BtnremoveClick(object sender, EventArgs e)
        {
            try
            {
                ReplaceWebPart(lstLinks.SelectedValue, txttofind.Text, string.Empty, false);
            }
            catch (Exception ex)
            {

              //  Loggings.LogError(ex);
            }
        }
        protected void BtnGenerateIdClick(object sender, EventArgs e)
        {
            string data = txtAssemblyName.Text;
            data += "|" + TxtTypeName.Text;
            byte[] dataBytes = Encoding.Unicode.GetBytes(data);
            MD5 hashAlgo = new MD5CryptoServiceProvider();
            byte[] hash = hashAlgo.ComputeHash(dataBytes);
            Guid hashGuid = new Guid(hash);
            TxtWebpartId.Text = hashGuid.ToString();
        }
        protected void BtnClearClick(object sender, EventArgs e)
        {
            txtAssemblyName.Text = string.Empty;
            TxtTypeName.Text = string.Empty;
        }
        public static string Val { get; set; }
        private static DataTable Executetotsql(string conn, SqlCommand query)
        {
            DataTable dt = new DataTable();
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    SqlConnection sqlConnection = new SqlConnection(conn);
                    sqlConnection.Open();
                    SqlCommand sqlCommand = sqlConnection.CreateCommand();
                    sqlCommand.CommandText = query.CommandText;
                    SqlDataReader reader = sqlCommand.ExecuteReader(CommandBehavior.CloseConnection);
                    dt.Load(reader);
                });
            }
            catch (Exception ex)
            {
            //    Loggings.LogError(ex);
            }
            return dt;
        }
        protected void BtnGetDatabasesClick(object sender, EventArgs e)
        {
            try
            {
                chkdbs.Items.Clear();
                SPWebApplication sPWebApplication = SPWebApplication.Lookup(new Uri(txtsiteurl.Text));
                SPContentDatabaseCollection contentDatabases = sPWebApplication.ContentDatabases;//.ContentDatabases();
                foreach (SPContentDatabase current in contentDatabases)
                {
                    if (current.DatabaseConnectionString != null)
                    {
                        string databaseConnectionString = current.DatabaseConnectionString;//
                    }
                    ListItem listItem = new ListItem();
                    listItem.Text = current.DisplayName;
                    listItem.Value = current.DatabaseConnectionString;
                    chkdbs.Items.Add(listItem);
                }
            }
            catch (Exception ex)
            {
               // Loggings.LogError(ex);
            }
        }
        protected void BtnSqlQueryExecuteClick(object sender, EventArgs e)
        {
            try
            {
                List<ListItem> list = (
                    from ListItem n in chkdbs.Items
                    where n.Selected
                    select n).ToList<ListItem>();
                DataTable dataTable = new DataTable();
                foreach (ListItem current in list)
                {
                    DataTable dataTable2 = Executetotsql(current.Value, BuildQuery(TxtWebpartId.Text));
                    if (dataTable2 != null && dataTable2.Rows.Count > 0)
                    {
                        dataTable.Merge(dataTable2);
                    }
                }
                gv_ResultQuery.DataSource = dataTable;
                gv_ResultQuery.DataBind();
            }
            catch (Exception ex)
            {
              //  Loggings.LogError(ex);
            }
        }
        private static SqlCommand BuildQuery(string wpInstance)
        {
            return new SqlCommand
                       {
         CommandText =string.Format(
                               "   SELECT DISTINCT WP.tp_WebPartTypeId AS [Instance ID], WP.tp_Class AS [Class Name], WP.tp_Assembly AS [Assembly Name], W.Title AS SiteTitle, D.DirName, D.LeafName, W.FullUrl AS WebURL, D.SiteId, D.WebId, D.Id AS DocumentId, WP.tp_ID AS WebPartSK FROM         dbo.Docs AS D WITH (nolock) INNER JOIN dbo.Webs AS W WITH (nolock) ON D.WebId = W.Id INNER JOIN dbo.WebParts AS WP WITH (nolock) ON D.Id = WP.tp_PageUrlID WHERE     (WP.tp_ListId IS NULL) AND (WP.tp_Type IS NULL) AND (WP.tp_Flags IS NULL) AND (WP.tp_BaseViewID IS NULL) AND  (WP.tp_WebPartTypeId = '{0}')", wpInstance)
        };
        }
        private string GetDbName(string connStr)
        {
            SqlConnectionStringBuilder sqlConnectionStringBuilder = new SqlConnectionStringBuilder
                                                                        {ConnectionString = connStr};
            string dataSource = sqlConnectionStringBuilder.DataSource;
            return sqlConnectionStringBuilder.InitialCatalog;
        }

        protected void BtnExecuteQueryClick(object sender, EventArgs e)
        {
            try
            {
                 List<ListItem> list = (
                    from ListItem n in chkdbs.Items
                    where n.Selected
                    select n).ToList<ListItem>();
                foreach (ListItem current in list)
                {
                    bool executed = ExecuteSqlQuery(current.Value, BuildExecQuery(TxtWebpartId.Text, txtrpgeneratedwpinstance.Text));
                }
            }
            catch (Exception)
            {
                
                throw;
            } 
        }
        private static bool ExecuteSqlQuery(string conn, SqlCommand query)
        {
            bool executed = false;
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    SqlConnection sqlConnection = new SqlConnection(conn);
                    sqlConnection.Open();
                    SqlCommand sqlCommand = sqlConnection.CreateCommand();
                    sqlCommand.CommandText = query.CommandText;
                   sqlCommand.ExecuteNonQuery();
                    executed = true;
                });
            }
            catch (Exception ex)
            {
                //    Loggings.LogError(ex);
            }
            return executed;
        }
        //executing replace query in sql
        private static SqlCommand BuildExecQuery(string oldwpInstance,string newwpInstance)
        {
            return new SqlCommand
            {
                CommandText = string.Format(
                                      "DECLARE @OldWebPartTypeId uniqueidentifier DECLARE @NewWebPartTypeId uniqueidentifier  SET @OldWebPartTypeId = '{0}' SET @NewWebPartTypeId = '{1}' UPDATE [WebParts] SET [tp_WebPartTypeId] = @NewWebPartTypeId WHERE [tp_WebPartTypeId] = @OldWebPartTypeId", oldwpInstance,newwpInstance)
            };
        }

        protected void BtnRpClearClick(object sender, EventArgs e)
        {
            txtrpassemblyname.Text = string.Empty;
            txtrptypename.Text = string.Empty;
        }

        protected void BtnRpGenerateIdClick(object sender, EventArgs e)
        {
            string data =txtrpassemblyname.Text;
            data += "|" + txtrptypename.Text;
            byte[] dataBytes = Encoding.Unicode.GetBytes(data);
            MD5 hashAlgo = new MD5CryptoServiceProvider();
            byte[] hash = hashAlgo.ComputeHash(dataBytes);
            Guid hashGuid = new Guid(hash);
            txtrpgeneratedwpinstance.Text = hashGuid.ToString();
        }
    }
}